package com.haoran.dwz.service.impl;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;

import com.haoran.dwz.dto.DwzGeneratorDTO;
import com.haoran.dwz.rest.R;
import com.haoran.dwz.security.AuthenticationHeader;
import com.haoran.dwz.service.DwzService;
import com.haoran.openapi.dwz.DwzServiceAPI;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DwzServiceRetrofitImpl implements DwzService {

	@Autowired
	private DwzServiceAPI dwzServiceAPI;

	@Autowired
	private AuthenticationHeader authenticationHeader;

	@Override
	public ResponseEntity<R> generate(String url, int type) {
		try {
			DwzGeneratorDTO dwzGeneratorDTO = new DwzGeneratorDTO(url, type);
			String content = com.alibaba.fastjson.JSONObject.toJSONString(dwzGeneratorDTO);
			Map<String, String> headers = authenticationHeader.create(content);

			Call<R> call = dwzServiceAPI.generate(headers.get(AuthenticationHeader.HEAD_KEY_KYE),
					headers.get(AuthenticationHeader.HEAD_KEY_ACCESS_TOKEN), dwzGeneratorDTO);
			boolean isAsync = false;
			if(isAsync) {
				asyncCall(call);
				return ResponseEntity.ok().build();
			}else {
				return syncCall(call);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.badRequest().build();
		}
	}

	/**
	 * 异步调用
	 * @param call
	 */
	private void asyncCall(Call<R> call) {
		call.enqueue(new Callback<R>() {
			@Override
			public void onResponse(Call<R> call, Response<R> response) {
				 ResponseEntity.ok(response.body());
			}
			
			@Override
			public void onFailure(Call<R> call, Throwable t) {
				
			}
		});
	}

	/**
	 * 同步处理
	 * @param call
	 * @return
	 * @throws IOException
	 */
	private ResponseEntity<R> syncCall(Call<R> call) throws IOException {
		/**  同步  start */
		Response<R> r = call.execute();
		if(r.isSuccessful()) {
			return ResponseEntity.ok(r.body());
		}else {
			return ResponseEntity.badRequest().build();
		}
		/** 同步 end*/
	}

}
